<!doctype html>
<html lang="en">
<head>
	<meta charset="UTF-8" />
	<title>Document</title>
	<style type="text/css">
		#canvas{
			border: 1px solid #aaa;
		}
		span{
			cursor: pointer;
			margin-left: 10px;
			text-decoration: underline;
			color: #aaa;
		}
	</style>
</head>
<body>
	<label for="">请输入验证码:<input type="text" name="" id="text" value="" /></label>
	<canvas id="canvas" width="90" height="30"></canvas>
	<span>刷新</span>
	<div>	
		<input type="submit" name="" id="sub" value="提交" />
	</div>
</body>
<script type="text/javascript">
	var canvas = document.getElementById("canvas");
	var ctx = canvas.getContext("2d")
	var span = document.querySelector("span")
	var	_text = document.getElementById("text");
	var sub = document.getElementById("sub")
	var text;
	num ();
	//点击刷新验证码
	span.onclick = function(){
		ctx.clearRect(0,0,90,30);
		num ();
	}
	//点击提交按钮
	sub.onclick = function(){
		if(_text.value.toUpperCase() == text.toUpperCase()){
			alert("验证码正确")	
		}else{
			alert("验证码错误")
		}
	}
	function num (){
		// 获取一个四位随机数
		var str = "abcdefghijklmnpqrstuvwxyzABCDEFGHIJKLMNPQRSTUVWXYZ123456789";
		var a = str[parseInt(Math.random()*str.length)]
		var b = str[parseInt(Math.random()*str.length)]
		var c = str[parseInt(Math.random()*str.length)]
		var d = str[parseInt(Math.random()*str.length)]
	/*	//随机颜色
		var color1 ="#"+ Math.floor(Math.random()*16777216).toString(16);
		var color2 ="#"+ Math.floor(Math.random()*16777216).toString(16);
		var color3 ="#"+ Math.floor(Math.random()*16777216).toString(16);
		var color4 ="#"+ Math.floor(Math.random()*16777216).toString(16);*/
		//渐变的随机数
		var colorRand1 = Math.random();
		var colorRand2 = Math.random();
		var colorRand3 = Math.random();
		var colorRand4 = Math.random();
		
		text = a+b+c+d;
		ctx.font = "30px Arial"
		var gradient = ctx.createLinearGradient(0,0,100,30);
		//渐变色
		gradient.addColorStop(colorRand1,"black");
		gradient.addColorStop(colorRand2,"green");
		gradient.addColorStop(colorRand3,"gray");
		gradient.addColorStop(colorRand4,"red");
		ctx.fillStyle = gradient;//笔触颜色
		ctx.fillText(text,0,25)

	}
	
</script>
</html>